<template>
  <div class="wrap">
    <bread-crumb :titleArr="titleArr" @back="back"></bread-crumb>
    <div class="data">
      <affix :label="$t('monitor.callNumMonitorList')" class="monitor-table">
        <table-data :allList="allServiceNums">
          <template slot="thead">
            <th><div class="cell" v-once>{{$t('monitor.serviceNum')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.externalCallToday')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.externalCallTodayAnswer')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.externalCallTodayMiss')}}</div></th>
            <!--<th><div class="cell" v-once>{{$t('monitor.todayConcurrAccessNum')}}</div></th>-->
            <th><div class="cell" v-once>{{$t('monitor.queuingNum')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.queuingLeak')}}</div></th>
          </template>
          <template slot="tbody" slot-scope="slotProps">
            <tr-common  v-for="(one, index) in slotProps.current" :key="index" :one="phoneServiceNums[one]" :header="header.callNum" @jumpIntoDetail="jumpIntoDetail"></tr-common>
          </template>
        </table-data>
      </affix>
      <affix :label="$t('monitor.callChannelSkillMonitorList')"  class="monitor-table">
        <template slot="questionSlot">
          <span @click.stop="openWarnConfigDialog" class="iconfont icon-peizhi" style="color: #459ae9;margin-right:6px;cursor:pointer;font-weight: normal;"></span>
          <el-tooltip class="item" effect="dark" popper-class="reportTip" placement="right" style="opacity: 1;">
            <div slot="content">
              {{$t('monitor.serviceTip')}}
            </div>
            <span class="tip"><i class="iconfont icon-wenzishuoming"></i></span>
          </el-tooltip>
        </template>
        <el-form :inline="true" :model="skillGroupForm">
          <el-form-item :label="$t('monitor.filterByQueue')">
            <el-select v-model="skillGroupForm.skillGroup" :placeholder="$t('monitor.filterByQueue')" multiple clearable filterable @change="skillGroupChange">
              <el-option
                v-for="item in cacheQueue"
                :key="item.Exten"
                :label="item.DisplayName"
                :value="item.Exten">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <table-data :allList="allQueue" :pageSizeChange="true">
          <template slot="thead">
            <th><div class="cell" v-once>{{$t('monitor.skillGroupName')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.loginAgentNum')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.spareAgent')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.callingAgentCount')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.busyAgentCount')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.queuingNum')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.queuingLeak')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.callSum')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.serviceLevel')}}</div></th>
            <!--<th><div class="cell" v-once>{{$t('monitor.spareAgent')}}</div></th>-->
            <!--<th><div class="cell" v-once>{{$t('monitor.checkInAgent')}}</div></th>-->
            <!--<th><div class="cell" v-once>{{$t('monitor.queueNumber')}}</div></th>-->
            <!--<th><div class="cell" v-once>{{$t('monitor.connectCallNumToday')}}</div></th>-->
          </template>
          <template slot="tbody" slot-scope="slotProps">
            <tr-queue  v-for="(one, index) in slotProps.current" :key="index" :one="phoneQueues[one]" :header="header.callSkill" @jumpIntoDetail="jumpIntoDetail"></tr-queue>
          </template>
        </table-data>
      </affix>
    </div>
    <el-dialog :title="$t('monitor.callQueueWarn')" append-to-body modal-append-to-body :visible.sync="warnDialog" :modal="true">
      <div v-for="(item, index) in warnConfig.config" :key="index" style="margin-bottom:16px;">
        <el-select v-model="item.queue" filterable :placeholder="$t('public.pleasePick')">
          <el-option
            v-for="item1 in cacheQueue"
            :key="item1.Exten"
            :label="item1.DisplayName"
            :value="item1.Exten">
          </el-option>
        </el-select>
        <el-select v-model="item.condition" :placeholder="$t('public.pleasePick')" style="margin:0 10px">
          <el-option
            v-for="item2 in conditionArr"
            :key="item2.value"
            :label="item2.label"
            :value="item2.value">
          </el-option>
        </el-select>
        <span style="margin-right:10px">{{$t('monitor.queuingNum')}}</span>
        <el-input class="condition right" :placeholder="$t('monitor.monitorRuleWarn')" style="width: 150px;margin-right:10px" v-model="item.value" size="mini"></el-input>
        <i @click.stop="addWarnConfig" class="el-icon-circle-plus" v-if="index < 1" style="color: #409EFF;font-size: 18px;cursor: pointer;"></i>
        <i @click.stop="deleteWarnConfig(index)" class="el-icon-remove" v-else style="color: #FF6B6B;font-size: 18px;margin-top: 4px;cursor: pointer;"></i>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="warnDialog=false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="saveWarnConfig(true)">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <QueueOrServiceNoDetail ref="queueDetailDialog" type='queue' :lineUpData="lineUpData"></QueueOrServiceNoDetail>
    <QueueOrServiceNoDetail ref="serviceDetailDialog" type='service' :lineUpData="lineUpData"></QueueOrServiceNoDetail>
  </div>
</template>
<script>
  import Affix from '../../ui-modules/affix/Affix'
  import BreadCrumb from '../../ui-modules/breadCrumb/BreadCrumbConfig'
  import tableData from './base/tableWrap'
  import trCommon from './base/TrCommon'
  import trQueue from './base/TrQueue'
  import QueueOrServiceNoDetail from './base/QueueOrServiceNoDetail'
  import {checkform} from '@/utils/validate.js'
import { deepClone } from '../../../utils/m7Utils'
  export default {
    name: 'callData',
    data () {
      return {
        titleArr: [this.$t('monitor.dataSummary'), this.$t('monitor.callDataSummary')],
        warnDialog: false,
        currentLineUpData: {},
        conditionArr: [
          {label: this.$t('public.equal'), value: 'equal'},
          {label: this.$t('public.moreThan'), value: 'over'},
          {label: this.$t('public.lessThan'), value: 'less'}
        ],
        lineUpData: [],
        warnConfig: {},
        cacheQueue: [],
        allQueue: Object.keys(window.phone_queues),
        allServiceNums: Object.keys(window.phone_serviceNos),
        header: {
          callNum: [{prop: 'serviceNoName', name: this.$t('monitor.serviceNum')},
            {prop: 'inCalls', name: this.$t('monitor.externalCallToday')},
            {prop: 'inComplete'},
            {prop: 'inLost', name: this.$t('monitor.externalCallTodayMiss')},
            // {prop: 'inLimit'},
            {prop: 'inQueueNow', color: 'red'},
            {prop: 'inQueueLeak'}
          ],
          callSkill: [{prop: 'queueName'},
            {prop: 'totalAgentCount', tooltip: true},
            {prop: 'idleAgentCount', tooltip: true},
            {prop: 'callingAgentCount', tooltip: true},
            {prop: 'busyStateAgentCount', tooltip: true},
            {prop: 'queueWaitCount', color: 'red'},
            {prop: 'queueAbandon'},
            {prop: 'linkCalls'},
            {prop: 'serviceLevel'}]
        },
        skillGroupForm:{
          skillGroup:[]
        }
      }
    },
    props: {
    },
    components: {
      Affix,
      BreadCrumb,
      tableData,
      trCommon,
      trQueue,
      QueueOrServiceNoDetail
    },
    inject: ['phoneServiceNums', 'phoneQueues', 'init'],
    methods: {
      jumpIntoDetail (data, type) {
        if (type === 'queue') {
          if (data.queueWaitCount <= 0) { // 排队数<= 0的时候，不打开弹窗
            return false
          }
          const currentQueue = window.phone_queues[data.queueId]
          if (currentQueue) {
            this.lineUpData = currentQueue.QueueEntryState || []
          }
          this.$nextTick(() => {
            this.$refs.queueDetailDialog.openDialog()
          })
        } else {
          if (data.inQueueNow <= 0) { // 排队数<= 0的时候，不打开弹窗
            return false
          }
          const currentService = window.phone_serviceNos[data.serviceNo]
          if (currentService) {
            this.lineUpData = currentService.QueueEntryState || []
          }
          this.$nextTick(() => {
            this.$refs.serviceDetailDialog.openDialog()
          })
        }
        this.currentLineUpData = data
      },
      closeQueueServiceDialog () {
        this.currentLineUpData = {}
      },
      back () {
        this.$emit('back')
      },
      openWarnConfigDialog () {
        this.warnDialog = true
        this.$store.dispatch('queryMonitorQueueWarningCfg', {pbx: this.$store.state.session.user.pbx}).then(resp => {
          this.warnConfig = resp.data || {config: [{ 'queue': '', 'value': '', 'condition': 'over' }], pbx: this.$store.state.session.user.pbx}
          const data = resp.data || {}
          this.$store.commit('monitor/QUEUE_WARNING', {data})
        })
      },
      addWarnConfig () {
        this.warnConfig.config.push({ 'queue': '', 'value': '', 'condition': 'over' })
      },
      deleteWarnConfig (index) {
        this.warnConfig.config.splice(index, 1)
      },
      saveWarnConfig () {
        let flag = false
        this.warnConfig.config.forEach(item => {
          if (!item.queue) { // 技能组没选 || 没填数量 || 没选条件
            flag = true
            this.$message.error(this.$t('call.placeSkillsGrouop'))
            return
          } else if (!item.value || (item.value && checkform(item.value, 'Number3'))) {
            this.$message.error(this.$t('monitor.monitorRuleWarn'))
            flag = true
            return
          }
        })
        if (!flag) { // 有不符合的条件
          this.$store.dispatch('updateMonitorQueueWarningCfg', this.warnConfig).then(resp => {
            if (resp && resp.success) {
              this.warnDialog = false
              this.$message.success(this.$t('monitor.saveSuccess'))
              const data = resp.data || {}
              this.$store.commit('monitor/QUEUE_WARNING', {data})
            }
          })
        }
      },
      skillGroupChange(val){
        // 选择技能组后看表格里数据是否存在该技能组，存在筛选，不存在为空（解决不存在时表格数据异常问题）
        if(val.length>0) {
          let newArr = []
          val.forEach(item=>{
            if(Object.keys(this.phoneQueues).includes(item)){
              newArr.push(item)
              this.allQueue = newArr
            } else {
              this.allQueue = []
            }
          })
        } else {
          this.allQueue = Object.keys(window.phone_queues)
        }
      }
    },
    watch: {
      '$store.state.monitor.updateCurrentQueueServiceNo'(evtJson){
        console.log(evtJson, 'watch进来了========')
        if (this.currentLineUpData && this.currentLineUpData !== {}) { // 排队详情的弹窗有打开
          if (this.currentLineUpData.type === 'queue' && evtJson.Queue === this.currentLineUpData.queueId) { // 当前弹窗打开 && 要更新的技能组数据跟当前打开弹窗一致
            const currentQueue = window.phone_queues[this.currentLineUpData.queueId]
            if (currentQueue) {
              this.lineUpData = currentQueue.QueueEntryState || []
            }
          } else if (this.currentLineUpData.type === 'service' && evtJson.ServiceNo === this.currentLineUpData.serviceNo) { // 当前弹窗打开 && 要更新的服务号数据跟当前打开弹窗一致
            const currentService = window.phone_serviceNos[this.currentLineUpData.serviceNo]
            if (currentService) {
              this.lineUpData = currentService.QueueEntryState || []
            }
          }
        }
      }
    },
    beforeMount () {
      this.init('phoneQueuesInit')
      this.init('phoneserviceNumsInit')
      this.$store.dispatch('getCache', {type: 'queues'}).then((res) => {
        const resList = res || []
        resList.filter(item=> item.PBX === this.$store.state.session.user.pbx)
        this.cacheQueue = resList
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl';
  .wrap
    padding 10px 16px 20px
  .data
    padding 10px
  .monitor-table
    padding-bottom 40px
  .icon-wenzishuoming
    color $c-main
    cursor pointer
    font-weight normal
</style>
